<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { VideoCamera, Search, StarFilled, ArrowDown } from '@element-plus/icons-vue'
import request from '@/utils/request.js'
import { pageMovies } from '@/api/movies'
import { profile, logout } from '@/api/user'

const router = useRouter()

// 轮播图（使用网络图片占位）
const carouselImages = ref([
  { src: 'https://images.unsplash.com/photo-1524985069026-dd778a71c7b4?auto=format&fit=crop&w=1600&q=80', title: '沉浸式观影', sub: 'IMAX · Dolby Atmos · 巨幕体验' },
  { src: 'https://img0.baidu.com/it/u=1167549078,741502639&fm=253&app=138&f=JPEG?w=1200&h=800', title: '电影与美食', sub: '爆米花的香与光影的浪漫' },
  { src: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.alicdn.com%2Fimgextra%2Fi1%2FO1CN01PHip1Q2JeKHLuxNEK_%21%214611686018427382982-0-rate.jpg&refer=http%3A%2F%2Fimg.alicdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1763432394&t=f99281cc5d7db68a38db886d35bbdd8f', title: '影院时刻', sub: '重逢经典与发现新作' },
  { src: 'https://pic.rmb.bdstatic.com/bjh/news/8153c51d2653be773af57811a89bf5e4.png', title: '光影中的科技', sub: '设备升级带来更佳画质' },
  { src: 'https://q8.itc.cn/q_70/images03/20250310/d812f9b753b244e09106c9c92c6aaea8.jpeg', title: '好片不断', sub: '每周精选推荐，不错过每一部好电影' },
])

// 搜索与结果
const keyword = ref('')
const loading = ref(false)
const results = ref([])
const quickTags = ['科幻', '动作', '喜剧', '悬疑', '爱情']

const onSearch = async () => {
  if (!keyword.value) {
    ElMessage.info('请输入关键字')
    return
  }
  loading.value = true
  try {
    const res = await request.get('/user/movies/search', {
      params: { keyword: keyword.value, pageNo: 1, pageSize: 12 },
    })
    if (res.code === '200') {
      results.value = res.data?.records || []
    } else {
      ElMessage.error(res.msg || '搜索失败')
    }
  } catch (e) {
    // 拦截器已统一处理错误
  } finally {
    loading.value = false
  }
}

const setTag = (tag) => {
  keyword.value = tag
  onSearch()
}

// 推荐占位数据（无搜索结果时展示）
const featured = ref([])

const fetchHot = async () => {
  try {
    const res = await pageMovies({ status: 'HOT', pageNo: 1, pageSize: 8 })
    if (res.code === '200') {
      featured.value = res.data?.records || []
    }
  } catch (e) {
    // 保持静默，首页仍可使用占位内容
  }
}

// 登录态与用户信息
const user = ref(null)
const loadUser = async () => {
  const token = localStorage.getItem('token')
  if (!token) return
  try {
    const res = await profile()
    if (res?.code === '200') user.value = res.data || null
  } catch {}
}
const displayName = computed(() => {
  const u = user.value
  return u?.nickname || u?.username || u?.uname || u?.name || '影迷'
})
const cleanUrl = (url) => (url ? String(url).replace(/`/g, '').trim() : '')
const avatarSrc = computed(() =>
  cleanUrl(user.value?.avatar || user.value?.avatarUrl || user.value?.imageUrl || user.value?.photo || user.value?.portrait)
)
const displayInitial = computed(() => displayName.value?.slice(0, 1))

// 移除旧的弹窗模式，改为路由跳转个人信息页
const onUserCommand = async (cmd) => {
  switch (cmd) {
    case 'profile': router.push('/me/profile'); break
    case 'saves': router.push('/me/saves'); break
    case 'orders': router.push('/me/orders'); break
    case 'comments': router.push('/me/comments'); break
    case 'logout':
      try { await logout() } catch {}
      localStorage.removeItem('token')
      user.value = null
      ElMessage.success('已退出登录')
      break
  }
}

onMounted(() => {
  fetchHot()
  loadUser()
})
const goLogin = () => router.push('/login')
const goRegister = () => router.push('/register')
const goDetail = (id) => router.push(`/movie/${id}`)
const goCinemas = () => router.push('/cinemas')
const goMovies = () => router.push('/movies')
const goMySaves = () => router.push('/me/saves')
const goMyOrders = () => router.push('/me/orders')
const goMyComments = () => router.push('/me/comments')
</script>

<template>
  <div class="home">
    <!-- 顶部导航 -->
    <div class="nav">
      <div class="brand">
        <el-icon size="22" class="brand-icon"><VideoCamera /></el-icon>
        <span class="brand-title">电影购票系统</span>
      </div>
      <div class="actions">
        <el-link @click="goCinemas">影院</el-link>
        <el-link @click="goMovies">全部电影</el-link>
        <el-link @click="goMySaves">我的收藏</el-link>
        <el-link @click="goMyOrders">我的订单</el-link>
        <el-link @click="goMyComments">我的评论</el-link>
        <template v-if="user">
          <el-dropdown placement="bottom-end" @command="onUserCommand">
            <span class="user-info" role="button">
              <el-avatar :src="avatarSrc" :size="28">{{ displayInitial }}</el-avatar>
              <span class="nick">{{ displayName }}</span>
              <el-icon class="caret"><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                <el-dropdown-item command="saves">我的收藏</el-dropdown-item>
                <el-dropdown-item command="orders">我的订单</el-dropdown-item>
                <el-dropdown-item command="comments">我的评论</el-dropdown-item>
                <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
        <template v-else>
          <el-link type="primary" @click="goLogin">登录</el-link>
          <el-link @click="goRegister">注册</el-link>
        </template>
      </div>
    </div>

    <!-- 英雄区 + 搜索 -->
    <section class="hero">
      <h1>发现好电影</h1>
      <p class="sub">购票 · 收藏 · 影评，一站式电影生活</p>
      <div class="search">
        <el-input
          v-model="keyword"
          placeholder="输入电影名称或类型，如：科幻/动作"
          size="large"
          class="search-input"
          @keyup.enter="onSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" size="large" :loading="loading" @click="onSearch">
          搜索
        </el-button>
      </div>
      <div class="tags">
        <span v-for="t in quickTags" :key="t" class="tag" @click="setTag(t)">{{ t }}</span>
      </div>
    </section>

    <!-- 轮播图 -->
    <section class="carousel-wrap">
      <el-carousel :interval="6000" height="420px" type="card">
        <el-carousel-item v-for="(item, idx) in carouselImages" :key="idx">
          <div class="slide">
            <img :src="item.src" alt="banner" />
            <div class="overlay">
              <div class="title">{{ item.title }}</div>
              <div class="sub">{{ item.sub }}</div>
            </div>
          </div>
        </el-carousel-item>
      </el-carousel>
    </section>

    <!-- 推荐 / 搜索结果 -->
    <section class="section">
      <div class="section-header">
        <h2>{{ results.length ? '搜索结果' : '为你推荐' }}</h2>
      </div>

      <div class="grid">
        <el-card
          v-for="(m, i) in (results.length ? results : featured)"
          :key="i"
          class="card clickable"
          shadow="hover"
          @click="m.id && goDetail(m.id)"
        >
          <div class="poster">
            <img :src="cleanUrl(m.posterUrl) || m.imageUrl || carouselImages[i % carouselImages.length].src" :alt="m.mname || m.title" />
          </div>
          <div class="info">
            <div class="name">{{ m.mname || m.title }}</div>
            <div class="meta">
              <span class="type">{{ m.type || '电影' }}</span>
              <span class="rating" v-if="(m.rating || m.score)">
                <el-icon class="star"><StarFilled /></el-icon>
                {{ (m.rating || m.score).toFixed ? (m.rating || m.score).toFixed(1) : (m.rating || m.score) }}
              </span>
            </div>
          </div>
        </el-card>
      </div>
    </section>
  </div>
</template>

<style scoped>
.home {
  min-height: 100vh;
  background:
    radial-gradient(1200px 600px at 15% 20%, #101317 0%, #0b0e12 40%, #06080b 100%),
    linear-gradient(180deg, #0b0f15 0%, #0d1117 100%);
}

/* 顶部导航 */
.nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
}
.brand { display: flex; align-items: center; gap: 8px; color: #e5eaf3; }
.brand-icon { color: #ffd04b; }
.brand-title { font-weight: 600; letter-spacing: .5px; }
.actions :deep(.el-link) { margin-left: 12px; }
.actions .user-info { display: inline-flex; align-items: center; gap: 8px; margin-left: 12px; color: #e5eaf3; cursor: pointer; }
.actions .nick { font-weight: 500; }
.actions .caret { color: #cfd3dc; }

.profile-card { display: flex; align-items: center; gap: 14px; }
.profile-card .info .name { font-weight: 600; font-size: 16px; }
.profile-card .row { color: #606266; font-size: 13px; margin-top: 6px; }

/* 英雄区 */
.hero {
  text-align: center;
  padding: 28px 24px 10px;
}
.hero h1 { margin: 0; font-size: 32px; color: #e5eaf3; }
.hero .sub { margin-top: 6px; color: #a8b0bb; }
.search { margin-top: 16px; display: inline-flex; gap: 8px; }
.search-input { width: min(620px, 90vw); }
.tags { margin-top: 10px; }
.tag {
  display: inline-block;
  padding: 6px 10px;
  margin-right: 8px;
  border-radius: 999px;
  background: rgba(255,255,255,.08);
  color: #cfd3dc;
  cursor: pointer;
  transition: all .2s ease;
}
.tag:hover { background: rgba(255,255,255,.12); color: #fff; }

/* 轮播 */
.carousel-wrap { padding: 12px 24px 0; }
.slide { position: relative; height: 100%; border-radius: 12px; overflow: hidden; }
.slide img { width: 100%; height: 100%; object-fit: cover; display: block; }
.overlay {
  position: absolute; inset: auto 0 0 0; padding: 12px 16px;
  background: linear-gradient(180deg, rgba(0,0,0,0) 0%, rgba(0,0,0,.55) 100%);
  color: #e5eaf3;
}
.overlay .title { font-size: 18px; font-weight: 600; }
.overlay .sub { margin-top: 2px; color: #cfd3dc; }

/* 区块 */
.section { padding: 18px 24px 28px; }
.section-header h2 { margin: 0 0 10px; color: #e5eaf3; }

/* 网格卡片 */
.grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 14px;
}
@media (max-width: 1200px) { .grid { grid-template-columns: repeat(3, 1fr); } }
@media (max-width: 900px) { .grid { grid-template-columns: repeat(2, 1fr); } }
@media (max-width: 600px) { .grid { grid-template-columns: 1fr; } }

.card :deep(.el-card__body) { padding: 0; overflow: hidden; }
.poster img { width: 100%; height: 240px; object-fit: cover; display: block; }
.info { padding: 10px 12px; }
.name { font-weight: 600; color: #1f2b38; }
.meta { margin-top: 4px; display: flex; align-items: center; gap: 8px; color: #606266; }
.star { color: #ffd04b; margin-right: 2px; }
.clickable { cursor: pointer; }
</style>